package team.se.tms.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import team.se.tms.annotation.CheckFormat;
import team.se.tms.annotation.SpecialCheck;
import team.se.tms.dao.impl.DaoImpl;
import team.se.tms.dto.*;
import team.se.tms.exception.SelectException;
import team.se.tms.factory.ModelFactory;
import team.se.tms.dto.AssignmentFile;
import team.se.tms.dto.AssignmentRelevantDataDetail;
import team.se.tms.dto.Page;
import team.se.tms.dto.ParameterPage;
import team.se.tms.po.AssignmentInfo;
import team.se.tms.po.LabelInfo;
import team.se.tms.po.ProjectInfo;
import team.se.tms.po.TaskScoreInfo;
import team.se.tms.service.AssignmentInfoService;
import team.se.tms.util.FileUtil;

import java.util.*;

/**
 * Created by argentum on 2018/12/7.
 * @author argentum
 */
@Slf4j
@Service("assignmentInfoService")
public class AssignmentInfoServiceImpl extends BaseServiceImpl implements AssignmentInfoService {

    @Autowired
    DaoImpl dao;

    /**
     * 根据用户id与任务id获取作业信息
     *
     * @param userId 用户id
     * @param taskId 任务id
     * @return 作业信息
     * @throws Exception 异常
     * @create on 2018/12/31 by winkyle
     */
    @Override
    public AssignmentFile getAssignmentFile(@SpecialCheck("Pk")String userId, @SpecialCheck("Pk")String taskId) throws Exception {
        return FileUtil.analysisAssignmentFile(dao.selectOne("AssignmentInfoMapper.selectAssignmentInfoByUserIdAndTaskId",getParameterMap("userId",userId,"taskId",taskId)));
    }

    /**
     * 根据用户id与任务id获取作业详细信息
     *
     * @param userId 用户id
     * @param taskId 任务id
     * @param page 分页
     * @return 作业详细信息列表
     * @throws Exception 异常
     * @create on 2019/1/1 by winkyle
     */
    @Override
    public List<AssignmentRelevantDataDetail> listAssignmentRelevantDataDetails(@SpecialCheck("Pk")String userId, @SpecialCheck("Pk")String taskId, @SpecialCheck("Pk")String teachCourseId, Page page) throws Exception {
        return FileUtil.analysisAssignmentRelevantDataDetails(dao.selectList("AssignmentInfoMapper.selectAssignmentRelevantDataDetailsByAttr",getParameterPage(page,"userId",userId,"taskId",taskId,"teachCourseId",teachCourseId)));
    }

    /**
     * @create on 2018/12/7 by argentum
     * @update on 2018/12/18 by argentum
     *
     * @param projectIds
     * @param type 0时下载最新，1时下载全部
     * @return
     */
    @Override
    public List<AssignmentFile> listAssignmentInfos( List<String> projectIds, int type) throws Exception{
        List<AssignmentInfo> assignmentInfos = new ArrayList<AssignmentInfo>();
        System.out.println("========/////========="+projectIds.get(0));
        if(type == 1){
            assignmentInfos = dao.selectList("AssignmentInfoMapper.selectAllAssignmentInfoListByProjectIds",projectIds);
        }
        if(type == 0){
           assignmentInfos = dao.selectList("AssignmentInfoMapper.selectLatestAssignmentInfoListByProjectIds",projectIds);
        }
        System.out.println(assignmentInfos);
        List<AssignmentFile> assignmentFiles = FileUtil.analysisAssignmentFiles(assignmentInfos);
        if(assignmentFiles!=null){
            return assignmentFiles;
        }
        throw new SelectException("查询结果为空");
    }

    /**
     * @create on 2018/12/7 by argentum
     * @update on 2018/12/7 by argentum
     *
     * @param assignmentIds
     * @return
     */
    @Override
    public Boolean modifyAssignmentLoadStates(List<String> assignmentIds) throws Exception {
        int result=0;
        result = dao.update("AssignmentInfoMapper.updateAssignmentLoadStatesByAssignmentId",assignmentIds);
        if(result == assignmentIds.size()){
            return true;
        }
        return false;
    }

    /**
     * 查询当前授课下所有作业
     *
     * @create on 2018/12/18 by argentum
     * @update on 2018/12/31 by argentum
     *
     * @param page
     * @param teachCourseId
     * @return
     * @throws Exception
     */
    @Override
    public List<AssignmentRelevantDataDetail> listAssignmentDetails(Page page, String teachCourseId) throws Exception {
        ParameterPage parameterPage = new ParameterPage();
        parameterPage.put("teachCourseId",teachCourseId);
        parameterPage.setPage(page);
        List<AssignmentRelevantDataDetail> assignmentRelevantDataDetails = dao.selectList("AssignmentInfoMapper.selectAssignmentDetailsByTeachCourseId",parameterPage);
        for (int i = 0; i <assignmentRelevantDataDetails.size() ; i++) {
            String[] type = assignmentRelevantDataDetails.get(i).getAssignmentAddress().split("\\.");
            if(type.length>1){
                //System.out.println(type[0]+"########"+type[1]);
                assignmentRelevantDataDetails.get(i).setAssignmentType(type[1]);
            }
            //System.out.println("assignmentRelevantDataDetails===================="+assignmentRelevantDataDetails.get(i).getAssignmentAddress());
        }
        return assignmentRelevantDataDetails;
    }

    /**
     * 查询该项目的所有作业信息
     *
     * @param projectId 项目ID
     * @return List<AssignmentFile>
     * @throws Exception 异常
     * @create on 2019/1/2 by sunddly
     */
    @Override
    public List<AssignmentFile> listAssignmentFiles(Page page, String projectId) throws Exception {
        ParameterPage parameterPage =new ParameterPage();
        parameterPage.put("projectId",projectId);
        parameterPage.setPage(page);
        List<AssignmentInfo> assignmentInfoList =dao.selectList("AssignmentInfoMapper.selectAssignmentInfosByProjectId",parameterPage);
        System.out.println("2^^^^^^^^^^^^^^^"+assignmentInfoList);
        List<AssignmentFile> assignmentFileList = FileUtil.analysisAssignmentFiles(assignmentInfoList);
        System.out.println("2^^^^^^^^^^^^^^^"+assignmentFileList);
        return assignmentFileList;
    }

    /**
     * 上传任务作业
     * @create on 2018/12/29 by argentum
     * @update on 2018/12/30 by argentum
     *
     * @param assignmentInfo
     * @param multipartFile
     * @return 上传结果
     * @throws Exception
     */
    @Override
    public Boolean saveTaskAssignmentInfo(String userId,String teachCourseId,AssignmentInfo assignmentInfo, MultipartFile multipartFile) throws Exception {
        String stuId = dao.selectOne("StudentInfoMapper.selectStuIdByUserId",userId);
        String taskId = assignmentInfo.getTaskId();
        assignmentInfo.setStuId(stuId);
        System.out.println("================="+stuId);
        Map<String,Object> map = new HashMap<>();
        map.put("stuId",stuId);
        map.put("taskId",taskId);
        //怎么处理项目id和阶段id和版本号
        assignmentInfo.setAssignmentVersion(1);//？
        AssignmentInfo assignment = dao.selectOne("AssignmentInfoMapper.selectAssignmentInfoByStuIdAndTaskId",map);
        int count;
        if(assignment!=null){
            assignmentInfo = ModelFactory.packageAssignmentInfo(assignmentInfo,multipartFile,0);
            count = dao.update("AssignmentInfoMapper.updateAssignmentInfoByStuIdAndTaskId",assignmentInfo);
        }else{
            assignmentInfo = ModelFactory.packageAssignmentInfo(assignmentInfo,multipartFile,1);
            List<ProjectInfo> projectInfos = dao.selectList("ProjectInfoMapper.selectMyProjectInfoByTeachCourseIdAndUserId",getParameterMap("userId",userId,"teachCourseId",teachCourseId));
            String projectId = null;
            if(projectInfos!=null&&projectInfos.size()>=1){
                projectInfos.get(0).getProjectId();
            }
            assignmentInfo.setProjectId(projectId);
            count = dao.insert("AssignmentInfoMapper.insertAssignmentInfo",assignmentInfo);
        }
        if(count<=0){
            throw new Exception("上传失败"+count);
        }
        return true;
    }

    /**
     * 获取该任务文档标签及小组成员的任务分数
     * @create on 2018/12/29 by argentum
     *
     * @param assignmentId
     * @return
     * @throws Exception
     * @update on 2019/3/21 by winkyle
     */

    @Override
    public JudgeDetail getJudgeDetail(@SpecialCheck("Pk") String assignmentId) throws Exception {
        return dao.selectOne("AssignmentInfoMapper.selectJudgeDetailByAssignmentId",assignmentId);
    }

    /**
     * 查询流程作业详情
     *
     * @param assignmentId 作业id
     * @param teaId 教师id
     * @return JudgeDetail 作业详情
     * @throws Exception 异常
     * @create on 2019/1/1 by sunddly
     */
    @Override
    public JudgeDetail getJudgeDetailInfo(String assignmentId, String teaId) throws Exception{
        JudgeDetail judgeDetail = new JudgeDetail();
        List<LabelInfo> labelInfos = dao.selectList("LabelInfoMapper.selectLabelInfoByAssignmentId",assignmentId);
        String teaName = dao.selectOne("TeacherInfoMapper.selectTeacherNameByTeaId",teaId);
        judgeDetail.setLabelInfos(labelInfos);
        judgeDetail.setTeaName(teaName);
        return judgeDetail;
    }

    /**
     * 查询作业信息
     *
     * @param assignmentId 作业Id
     * @return 作业地址
     * @throws Exception 异常
     * @create on 2018/12/27 by sunddly
     */
    @Override
    public AssignmentFile getAssignmentFile(String assignmentId) throws Exception {
        AssignmentInfo assignmentInfo = dao.selectOne("AssignmentInfoMapper.selectAssignmentInfoByAssignmentId",assignmentId);
        AssignmentFile assignmentFile = new AssignmentFile();
        if (assignmentInfo!=null){
            assignmentFile.setAssignmentId(assignmentInfo.getAssignmentId());
            assignmentFile.setAssignmentName(assignmentInfo.getAssignmentName());
            assignmentFile.setAssignmentAddress(assignmentInfo.getAssignmentAddress());
            assignmentFile.setAssignmentJudgeAddress(assignmentInfo.getAssignmentJudgeAddress());
            //assignmentFile.setAssignmentState(assignmentInfo.getAssignmentState());
            assignmentFile.setAssignmentCreateTime(assignmentInfo.getAssignmentCreateTime());
            assignmentFile.setAssignmentUpdateTime(assignmentInfo.getAssignmentUpdateTime());
            assignmentFile.setAssignmentJudgeCreateTime(assignmentInfo.getAssignmentJudgeCreateTime());
            assignmentFile.setAssignmentJudgement(assignmentInfo.getAssignmentJudgement());
            assignmentFile.setTaskType(assignmentInfo.getTaskType());
            assignmentFile.setProjectId(assignmentInfo.getProjectId());
            assignmentFile.setTaskId(assignmentInfo.getTaskId());
            assignmentFile.setStuId(assignmentInfo.getStuId());
            assignmentFile.setTeaId(assignmentInfo.getTeaId());
            assignmentFile.setStageId(assignmentInfo.getStageId());
        }
        assignmentFile = FileUtil.analysisAssignmentFile(assignmentFile);
        return assignmentFile;
    }
    /**
     * 查询最新的作业信息
     *
     * @param projectId 项目Id
     * @return 作业信息
     * @throws Exception 异常
     * @create on 2018/12/26 by sunddly
     */
    @Override
    public AssignmentInfo getLatestAssignmentAppraiseState(String projectId) throws Exception {
        AssignmentInfo assignmentInfo = new AssignmentInfo();
//        Map<String,Object> map = new HashMap<>();
//        map.put("projectId",projectId);
//        map.put("stageId",stageId);
        assignmentInfo = dao.selectOne("AssignmentInfoMapper.selectLatestAssignmentInfoByProjectId",projectId);

        return assignmentInfo;
    }
    /**
     * 保存作业信息
     *
     * @param assignmentInfo 作业信息
     * @param multipartFile 文件
     * @param type 保存类型,0则更新，1则插入
     * @return result
     * @throws Exception 异常
     * @create on 2018/12/27 by sunddly
     * @update on 2018/12/30 by argentum
     */
    @Override
    public Boolean saveFlowAssignment(AssignmentInfo assignmentInfo, MultipartFile multipartFile, int type) throws Exception {
        AssignmentInfo newAssignmentInfo;
        System.out.println("%%%%%%%%%%%%%%%newAssignmentInfo"+assignmentInfo.getAssignmentVersion());
        newAssignmentInfo = ModelFactory.packageAssignmentInfo(assignmentInfo,multipartFile,type);
        System.out.println("%%%%%%%%%%%%%%%newAssignmentInfo"+newAssignmentInfo.getAssignmentVersion());
        if(type==0 ){
            if((int)dao.update("AssignmentInfoMapper.updateAssignmentInfoByAssignmentId",newAssignmentInfo)>0){
                return true;
            }
        }else if(type==1){
            assignmentInfo.setStuId("6286464865");
            if ((int)dao.insert("AssignmentInfoMapper.insertAssignmentInfo",newAssignmentInfo)>0){
                return true;
            }
        }
        return false;
    }
    public Boolean deleteAssignmentFile(String filePath){
        boolean result = true;
        try{
            FileUtil.destroyFile(filePath);
        }catch (Exception e){
            result =false;
        }
        return result;
    }
}
